﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ultimus.OC;
using Ultimus.WFServer;
using H2.NET.Common;

namespace H2.NET.Web.Workflow
{
    public partial class Inbox3 : DwzCode.BasePage
    {
        #region 属性 public
        private DataTable dt = new DataTable();
        private DataTable allProcess = new DataTable();

        [SessionType]
        string strProcessName = "";

        public string Type
        {
            get
            {
                return this.ViewState["Type"] == null ? "" : (String)this.ViewState["Type"];
            }
            set
            {
                this.ViewState["Type"] = value;
            }
        }
        #endregion

        #region 事件 页面 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                strProcessName = Request.QueryString["process"];

                load_gv_inbox_list();
                //第一次加载页面时初始化
                hf_type.Value = AksRequest.GetString("drpProcess").Trim();
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 Page_Load 事件出错：" + ee.Message);
            }
        }
        #endregion


        private string BuildSqlStr()
        {
            string strUserName = clsCmm.comm_username;
            string strSummary = tb_Summary.Text.Trim().Replace(",", "',").Replace("'", "''");
            string strIncidentNoFrom = txtIncidentFrom.Value;
            string strIncidentNoTo = txtIncidentTo.Value;

            //查询过滤中Process下拉列表中的值
            string strProcess = "all";
            if (drpProcess.SelectedItem != null)
            {
                strProcess = drpProcess.SelectedItem.Value.Trim();
            }

            //查询过滤中流程步骤的值
            string strStep = "all";
            if (drpStep.SelectedItem != null)
            {
                strStep = drpStep.SelectedItem.Value.Trim();
            }

            var strSql = new StringBuilder();
            strSql.Append(
                @"SELECT DISTINCT
                        '' AS initiator_name ,
                        '' AS taskuser_name ,
                        '' AS assignedtouser_name,
                    ").Append(Environment.NewLine);

            strSql.Append(@"RTRIM(a.taskid) AS taskid").Append(Environment.NewLine);
            //中文的情况，流程名变化
            if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
            {
                strSql.Append(" ,h.processhelpurl as processname3").Append(Environment.NewLine);
                strSql.Append(" ,h.processname").Append(Environment.NewLine);
            }
            else
            {
                strSql.Append(" ,a.processname as processname3").Append(Environment.NewLine);
                strSql.Append(" ,a.processname").Append(Environment.NewLine);
            }

            strSql.Append(" ,rtrim(a.helpurl) as helpurl").Append(Environment.NewLine);
            strSql.Append(" ,'' as openform").Append(Environment.NewLine);

            strSql.Append(" ,a.incident").Append(Environment.NewLine);
            strSql.Append(" ,a.steplabel").Append(Environment.NewLine);
            strSql.Append(" ,a.taskuser").Append(Environment.NewLine);
            strSql.Append(" ,a.assignedtouser").Append(Environment.NewLine);
            strSql.Append(" ,'' as img_status").Append(Environment.NewLine);     //状态图标
            strSql.Append(" ,'' as img_monitor").Append(Environment.NewLine);    //监控图标
            strSql.Append(" ,a.status").Append(Environment.NewLine);
            strSql.Append(" ,a.substatus").Append(Environment.NewLine);
            strSql.Append(" ,a.starttime").Append(Environment.NewLine);
            strSql.Append(" ,a.delaytime").Append(Environment.NewLine);
            strSql.Append(" ,a.overduetime").Append(Environment.NewLine);
            strSql.Append(" ,a.urgentduetime").Append(Environment.NewLine);

            strSql.Append(" ,i.summary ").Append(Environment.NewLine);
            strSql.Append(" ,i.status AS i_status").Append(Environment.NewLine);
            strSql.Append(" ,i.priority").Append(Environment.NewLine);
            strSql.Append(" ,i.initiator").Append(Environment.NewLine);

            strSql.Append(
                @"FROM    tasks a WITH (NOLOCK)
        LEFT JOIN initiate h WITH (NOLOCK) ON a.processname = h.processname
        LEFT JOIN dbo.PROCESSES p WITH (NOLOCK) ON h.PROCESSNAME = p.PROCESSNAME
        LEFT JOIN dbo.INCIDENTS i WITH (NOLOCK) ON h.PROCESSNAME = i.PROCESSNAME
                                     AND a.INCIDENT = i.INCIDENT
        LEFT JOIN dbo.BPMSYSTEM s WITH (NOLOCK) ON p.DESCRIPTION = s.KeyWords").Append(Environment.NewLine);
            strSql.Append("LEFT JOIN dbo.TASKQUEUE tq WITH (NOLOCK) ON a.TASKID = tq.TASKID").Append(Environment.NewLine);

            strSql.Append(
                @"WHERE     a.assignedtouser = '" + strUserName + @"' COLLATE Chinese_PRC_CI_AI
                    AND tq.TASKID IS NULL").Append(Environment.NewLine);
            strSql.Append("AND s.Platform = '" +
                          Util.AppSettings("platform") + "'").Append(Environment.NewLine);

            //如果是 Cancel 的情况
            //if (e_element_tr_search.Value == "block" && e_element_tr_cancel.Value == "block")
            //{
            //    strSql.Append(" and a.status=1").Append(Environment.NewLine);   //加上后，系统会自动增加(仅被退回的情况，才允许 Cancel)
            //    strSql.Append(" and (rtrim(a.steplabel) + rtrim(a.stepid)) in(select rtrim(steplabel) + rtrim(stepid) from processsteps where steptype=2)").Append(Environment.NewLine);
            //    strSql.Append(" and a.assignedtouser = '" + strUserName + "' COLLATE Chinese_PRC_CI_AI").Append(Environment.NewLine);
            //    strSql.Append(" and (rtrim(a.processname) + rtrim(a.incident)) in (select (rtrim(processname) + rtrim(incident)) from incidents where status=1 and lower(initiator)=lower('" + strUserName + "'))").Append(Environment.NewLine);
            //}
            //else
            //{
            strSql.Append("AND CHARINDEX('B', a.STEPID) > 0").Append(Environment.NewLine);

            strSql.Append("AND i.initiator = '" + strUserName + "' COLLATE Chinese_PRC_CI_AI ").Append(Environment.NewLine);
            //if (this.Type != "1")
            //    strSql.Append("AND i.status=1").Append(Environment.NewLine);
            //}

            //查询过滤
            if (strProcess != "all")
            {
                strSql.Append("and a.processname = '" + strProcess + "'").Append(Environment.NewLine);
            }

            //added by
            if (!string.IsNullOrEmpty(strProcessName))
            {
                strSql.Append(" and a.processname = '" + strProcessName + "'").Append(Environment.NewLine);
            }

            if (strIncidentNoFrom != "")
            {
                strSql.Append(" and a.incident >= " + strIncidentNoFrom + "").Append(Environment.NewLine);
            }

            if (strStep != "all")
            {
                strSql.Append(" and a.steplabel = '" + strStep + "'").Append(Environment.NewLine);
            }

            if (strIncidentNoTo != "")
            {
                strSql.Append(" and a.incident <= " + strIncidentNoTo + "").Append(Environment.NewLine);
            }

            if (strSummary != "")
            {
                strSql.Append(" and i.summary like '%" + strSummary + "%'").Append(Environment.NewLine);
            }
            return strSql.ToString();
        }

        private string AppendForCount(string sqlStr)
        {
            return string.Format("select count(1) from ({0}) sub", sqlStr);
        }

        private string AppendForPaged(string sqlstr, int start, int end)
        {
            string orderby = "starttime desc";

            return string.Format(";with temp as(\r\n" +
                "	select row_number() over(order by sub.{3}) as rownum, sub.* from ({0}) sub\r\n)\r\n" +
                "select * from temp where rownum between {1} and {2}", sqlstr, start, end, orderby);
        }

        private DataTable PagedQuery()
        {
            clsCmm.clsDB.Storage("bpmDB");
            string sql = BuildSqlStr();
            TotalItemCount = Convert.ToInt32(clsCmm.clsDB.Query(AppendForCount(sql)).Rows[0][0]);
            PageNumber = Convert.ToInt32(Request.Form["pageNum"] ?? "1");

            Pager1.TotalItemCount = TotalItemCount;
            Pager1.PageSize = PageSize;
            Pager1.PageNumber = PageNumber;
            dt = clsCmm.clsDB.Query(AppendForPaged(sql, PageSize * (PageNumber - 1) + 1, PageSize * PageNumber));

            return dt;
        }

        #region 方法 查询并对列表进行数据绑定
        public void load_gv_inbox_list()
        {
            try
            {
                //加载列表
                dt = PagedQuery();
                allProcess = get_all_process();
                initSelectItem();
                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region added by zk 2009-12-21 start
                //取得所有的用户账号对应用户姓名             
                string str_user_name = "";
                DataTable dt2 = new DataTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //initiator
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                    }

                    //taskuser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'";
                    }

                    //assignedtouser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'";
                    }
                }

                //从数据库中查询用户信息
                string strSQL = "select rtrim(FULLNAME) as UserFullName,lower(rtrim(Name)) as UserShortName from JOBS where lower(rtrim(Name)) in('-1'" + str_user_name + ")";
                clsCmm.clsDB.Storage("bpmDB");
                dt2 = clsCmm.clsDB.Query(strSQL);
                #endregion added by zk 2009-12-21 end

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();
                    if (!string.IsNullOrEmpty(HelpUrl) && HelpUrl.Length >= 5 && HelpUrl.Substring(0, 5).ToLower() == "form:")
                    {
                        dt.Rows[i]["openform"] = HelpUrl.Substring(5, HelpUrl.Length - 5);
                    }
                    else
                    {
                        dt.Rows[i]["openform"] = "workflow/openform.aspx";
                    }

                    #region SMD项目特殊处理

                    var processName = dt.Rows[i]["processname"].ToString().Trim();
                    if (processName == "New Store Application" ||
                        processName == "Store Deposit Change" ||
                        processName == "Store Deposit Receive" ||
                        processName == "Store Data Change" ||
                        processName == "MDC Itss")
                    {
                        dt.Rows[i]["openform"] = "pages/smd/taskview.aspx";
                    }

                    #endregion

                    #region added by zk 2009-12-21 start
                    //循环设置用户信息
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        //initiator
                        if (dt.Rows[i]["initiator"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["initiator_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //taskuser
                        if (dt.Rows[i]["taskuser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["taskuser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //assignedtouser
                        if (dt.Rows[i]["assignedtouser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["assignedtouser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }
                    }
                    #endregion added by zk 2009-12-21 end

                    //流程状态图标
                    if (dt.Rows[i]["i_status"].ToString() == "1")
                    {
                        dt.Rows[i]["img_status"] = "frm_complete_pending.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_status"] = "frm_complete_complete.gif";
                    }

                    //判断是否为指派、会办的任务类型
                    if (dt.Rows[i]["taskuser"].ToString() != dt.Rows[i]["assignedtouser"].ToString())
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                    }

                    //是否显示监控图标
                    if (dt.Rows[i]["taskid"] == DBNull.Value || dt.Rows[i]["taskid"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["img_monitor"] = "frm_initiate_blank.gif";
                        dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_monitor"] = "bpmview.gif";
                    }

                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "starttime DESC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                gvInbox.DataSource = dt;
                gvInbox.DataBind();
                

            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_gv_inbox_list 方法出错：" + ee.Message);
            }
        }
        #endregion

        public void load_drp_control_list()
        {
            try
            {
                //清空现有列表
                drpProcess.Items.Clear();

                //增加第一行
                drpProcess.Items.Add(new ListItem("All", "all"));

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_drp_control_list方法出错：" + ex.Message);
            }
        }

        #region 获取全部流程
        public DataTable get_all_process()
        {
            string strSQL = @"SELECT DISTINCT  a.processname FROM    tasks a WITH (NOLOCK)
LEFT JOIN initiate h WITH (NOLOCK) ON a.processname = h.processname
LEFT JOIN dbo.PROCESSES p WITH (NOLOCK) ON h.PROCESSNAME = p.PROCESSNAME
LEFT JOIN dbo.INCIDENTS i WITH (NOLOCK) ON h.PROCESSNAME = i.PROCESSNAME AND a.INCIDENT = i.INCIDENT
LEFT JOIN dbo.BPMSYSTEM s WITH (NOLOCK) ON p.DESCRIPTION = s.KeyWords
LEFT JOIN dbo.TASKQUEUE tq WITH (NOLOCK) ON a.TASKID = tq.TASKID
WHERE     a.assignedtouser = '{username}' COLLATE Chinese_PRC_CI_AI
AND tq.TASKID IS NULL
AND s.Platform = 'MDC'
AND CHARINDEX('B', a.STEPID) > 0
AND i.initiator = '{username}' COLLATE Chinese_PRC_CI_AI ";
            strSQL = strSQL.Replace("{username}", clsCmm.comm_username);
            TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_inbox 方法SQL：" + strSQL);

            clsCmm.clsDB.Storage("bpmDB");
            allProcess = clsCmm.clsDB.Query(strSQL);
            return allProcess;
        }
        #endregion

        #region 获取流程的step
        public DataTable getStepByProcess(string process)
        {
            string strSQL = "select * from [PROCESSSTEPS] where processname='" + process + "' and steptype not in (2,3,5,7)";
            clsCmm.clsDB.Storage("bpmDB");
            return clsCmm.clsDB.Query(strSQL);
        }
        #endregion

        #region 加载选项卡的数据
        public void initSelectItem()
        {
            #region 加载drpProcess选项
            try
            {

                string oldProcess = drpProcess.SelectedValue;
                //清空现有列表
                drpProcess.Items.Clear();

                //增加第一行
                drpProcess.Items.Add(new ListItem("All", "all"));

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region 获取全部流程的流程名称
                for (int i = 0; i < allProcess.Rows.Count; i++)
                {
                    bool Flg = true;

                    //流程名称下拉列表
                    foreach (ListItem item in drpProcess.Items)
                    {
                        if (allProcess.Rows[i]["processname"].ToString() == item.Value)
                        {
                            Flg = false;
                            break;
                        }
                    }

                    //如果不存在的情况
                    if (Flg)
                    {
                        drpProcess.Items.Add(new ListItem(GetCache(allProcess.Rows[i]["processname"].ToString().Trim()), allProcess.Rows[i]["processname"].ToString().Trim()));
                    }
                }
                if (!oldProcess.Equals("all"))
                {
                    drpProcess.SelectedValue = oldProcess;
                }
                #endregion
            }
            catch (Exception ex)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_drp_control_list方法出错：" + ex.Message);
            }
            #endregion

            #region 加载processStep选项
            processStep();
            #endregion
        }

        #region processStep
        public void processStep()
        {
            String oldStep = drpStep.SelectedValue.Trim();
            drpStep.Items.Clear();
            //增加第一行
            drpStep.Items.Add(new ListItem("All", "all"));
            if (drpProcess.SelectedItem != null && drpProcess.SelectedItem.Value != "all")
            {
                DataTable steps = getStepByProcess(drpProcess.SelectedItem.Value.Trim());
                for (int i = 0; i < steps.Rows.Count; i++)
                {
                    drpStep.Items.Add(new ListItem(GetCache(steps.Rows[i]["steplabel"].ToString().Trim()), steps.Rows[i]["steplabel"].ToString().Trim()));
                }
            }

            if (!oldStep.Equals("all"))
            {
                drpStep.SelectedValue = oldStep;
            }
        }
        #endregion
        #endregion
    }
}